package com.xqh.service.impl.ques;

import com.xqh.base.common.ModifyCommonDto;
import com.xqh.base.dao.CrudMapper;
import com.xqh.base.exception.ServiceException;
import com.xqh.base.service.impl.BaseCrudServiceImpl;
import com.xqh.base.util.http.HttpClientUtils;
import com.xqh.base.util.id.IdWorker;
import com.xqh.common.Global;
import com.xqh.dao.ques.VocabularyMapper;
import com.xqh.entity.ques.Vocabulary;
import com.xqh.service.ques.VocabularyService;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

/**
 * 
 * @author leo
 * @date 2018-04-16 16:09:29
 * @version 1.0.0
 * @copyright www.vip-young.com
 */
@Service("vocabularyService")
public class VocabularyServiceImpl extends BaseCrudServiceImpl<Vocabulary> implements VocabularyService {

    @Resource
    private VocabularyMapper vocabularyMapper;

    @Override
    public CrudMapper init() {
        return vocabularyMapper;
    }

    @Override
    @Transactional
    public void batchUpdateVocab(List<Vocabulary> vlist) {
       vocabularyMapper.batchUpdateVocab(vlist);
    }

    @Override
    @Transactional
    public void modifyData(ModifyCommonDto dto) {

    }

    @Override
    @Transactional
    public int saveData(Vocabulary entity) throws ServiceException {
        Map<String,Object> map = new HashMap<>();
        map.put("text",entity.getText());
        int count = vocabularyMapper.selectCount(map);
        if(StringUtils.hasText(entity.getText())){
            if(entity.getText().contains(" ")){
                entity.setTextType(Vocabulary.PHRASE);
            }else{
                entity.setTextType(Vocabulary.WORD);
            }
        }
        entity.setCode(IdWorker.getStringCode());
        putEmptyStr(entity);
        if(count == 0){
            entity.setCreateDate(new Date());
            vocabularyMapper.insert(entity);
        }
        return -1;
    }

    public void putEmptyStr(Vocabulary entity){
        if(judgeWord(entity.getUkPhonetic())){
            entity.setUkPhonetic(Vocabulary.EMPTY);
        }
        if(judgeWord(entity.getUsPhonetic())){
            entity.setUsPhonetic(Vocabulary.EMPTY);
        }
        if(judgeWord(entity.getTranslationJson())){
            entity.setTranslationJson(Vocabulary.EMPTY);
        }
        if(judgeWord(entity.getExampleSentence())){
            entity.setExampleSentence(Vocabulary.EMPTY);
        }

        if(judgeWord(entity.getEnExplain())){
            entity.setEnExplain(Vocabulary.EMPTY);
        }
    }

    public boolean judgeWord(String word){
        if(StringUtils.isEmpty(word) || "null".equalsIgnoreCase(word)){
           return true;
        }
        return false;
    }

    @Override
    public List<String> filterUnSpiderWords(List<String> wordList) {
        Map<String,Object> map = new HashMap<>();
        map.put("wordList", wordList);
        List<Vocabulary> exists = findByBiz(map);
        Map<String,String> uniqueMap = new HashMap<>();

        List<String> unExists = new ArrayList<>();
        if(!CollectionUtils.isEmpty(exists)){
            for(Vocabulary v:exists){
                uniqueMap.put(v.getText(),"");
            }
        }
        for(String w:wordList){
            if(!uniqueMap.containsKey(w)){
                unExists.add(w);
            }
        }
        return unExists;
    }

    @Override
    @Transactional
    public void reUpdateData(Vocabulary vocab){
       Map<String,Object> map = new HashMap<>();
       map.put("text", vocab.getText());
       Vocabulary old = this.findOneByBiz(map);
       if(null != old){
           old.setUsPhonetic(vocab.getUsPhonetic());
           old.setUkPhonetic(vocab.getUkPhonetic());
           old.setTranslationJson(vocab.getTranslationJson());
           old.setExampleSentence(vocab.getExampleSentence());
           old.setEnExplain(vocab.getEnExplain());
           putEmptyStr(old);
           vocabularyMapper.updateByPrimaryKey(old);
       }
    }

    @Override
    @Transactional
    public void downloadAudio(Vocabulary vocab) {
       String path = Global.getConfig("vocabulary.path");
       String uk_path = path+File.separator+"uk";
       String us_path = path+File.separator+"us";
       String download_url = Global.getConfig("youdao.download.url");
       String us_url = download_url.concat("type=2&audio=");//下载美音路径
       String uk_url = download_url.concat("type=1&audio=");//下载 英音路径
       String word = vocab.getText();
        if(word.contains(" ")){
            try {
                word = URLEncoder.encode(word, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                logger.error("",e);
            }
        }
        boolean uk_flag = HttpClientUtils.downloadFile2(uk_url.concat(word), uk_path, vocab.getText().concat(".mp3"));
        boolean us_flag = HttpClientUtils.downloadFile2(us_url.concat(word), us_path, vocab.getText().concat(".mp3"));
        if(us_flag && uk_flag){
            logger.info("更新词汇 {} 音频信息.", vocab.getText());
            vocab.setAudioUrl(vocab.getText().concat(".mp3"));
            vocabularyMapper.updateByPrimaryKey(vocab);
        }
    }

    @Override
    public void uploadVocabAudio(Vocabulary vocab) {

    }

    public static void main(String[] args) {
        File file = new File("F:\\vocabulary\\above.mp3");
        System.out.println(file.exists());
    }
}